結合前面和 Slack 交流的經驗,以及對觸發器的了解,只要設定每天早上觸發一次,每次觸發就丟點資料到 Slack,這就是早報機器人的基本且核心的概念了。
以下範例拿 iThome 的 RSS 做示範(https://www.ithome.com.tw/rss.xml
)
function itToday() {
var url = 'https://www.ithome.com.tw/rss.xml';
var xml = UrlFetchApp.fetch(url).getContentText();
var items = parseRss(xml);
var slackAttachments = [];
for (var i in items) {
var item = items[i];
var title = item.getChildText('title');
var link = item.getChildText('link');
var pubDate = new Date(item.getChildText('pubDate')).toJSON();
slackAttachments.push({
color: '#00a0e9',
fields: [{
title: '標題',
value: '<' + link + '|' + title + '>',
short: true
}, {
title: '時間',
value: pubDate,
short: true
}]
});
}
postToSlack(slackAttachments);
}
function parseRss(xml) {
var doc = XmlService.parse(xml);
var root = doc.getRootElement();
var channel = root.getChild('channel');
var items = channel.getChildren('item');
return items;
}
function postToSlack (attachments) {
var webHookUrl = 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX';
var params = {
method: 'POST',
payload: JSON.stringify({
channel: '#general',
username: '熊俠',
icon_url: 'https://ithelp.ithome.com.tw/storage/image/ironman9theditor.png',
attachments: attachments
})
};
UrlFetchApp.fetch(webHookUrl, params);
}
順利的話,就能看到開頭那張成果圖了。